<template>
  <div class="concat_box">
    <customDialog
      :title="`剧目拼接-${title}`"
      :dialogVisible="dialogVisible"
      @close="closeDialog"
      @confirm="confirmDialog"
      width="1000"
    >
      <div class="search_box">
        <el-form :inline="true" :model="formData">
          <el-form-item label="剧目ID或标题">
            <el-input
              v-model="formData.operaName"
              placeholder="剧目ID或标题"
              clearable
            />
          </el-form-item>
          <el-form-item label="标 签">
            <el-select
              v-model="formData.tagIds"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in tagsOption"
                :key="item?.id"
                :label="item.text"
                :value="item?.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList(1)">查 询</el-button>
            <el-button type="primary" @click="resetList">重 置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table_box_wrapper">
        <div v-if="concatOperas.length > 0" class="opera">
          <span>
            该剧拼接的剧目为：
            <span class="blue" v-for="(item, i) in concatOperas" :key="i">
              {{ ` ${item.name}${i < concatOperas.length - 1 ? "、" : ""} ` }}
            </span>
          </span>
          <el-button
            type="primary"
            @click="clearBtn"
            :disabled="selectionData.length == 0"
            >清空选中</el-button
          >
        </div>
        <custom-table
          ref="customTableRef"
          :loading="loading"
          :columns="columns"
          :tableData="tableData"
          :pageObj="pageObj"
          @sizechange="sizechange"
          @currentChange="currentChange"
          :typeSelect="true"
          @selectionChange="selectionChange"
          :max-height="500"
          :reserveSelection="true"
          class="table_box"
        >
          <template #updateEpisodeNo="{ scope }">
            {{ `${scope.row?.updateEpisodeNo} / ${scope.row?.episodeNum}` }}
          </template>
          <template #tags="{ scope }">
            <el-tag
              v-for="(item, i) in scope.row?.tags"
              :key="i"
              style="margin: 0 3px"
            >
              {{ item.text }}
            </el-tag>
          </template>
          <template #promotionStartTime="{ scope }">
            <span v-if="activeTime(scope.row?.promotionStartTime)" class="red">
              {{ scope.row?.promotionStartTime }}
            </span>
            <el-tag type="success" v-else>已开投</el-tag>
          </template>
        </custom-table>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs } from "vue";
import customTable from "@/components/CustomTable/index.vue";
import customDialog from "@/components/CustomDialog/index.vue";
import {
  operasSearch,
  getConcatOperas,
  setConcatOperas,
} from "@/api/operateCenter/episode/index";
import moment from "moment";
import { cloneDeep } from "lodash-es";

const customTableRef = ref();
const dialogVisible = ref(false);
const loading = ref<boolean>(false);
const tagsOption = ref<Array<any>>([]);
const tableData = ref<Array<any>>([]);
const selectionData = ref<Array<any>>([]);
const form = {
  operaName: "",
  tagIds: [],
  pageNo: 1,
  pageSize: 10,
};

const formData = reactive(Object.assign({}, form));
interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});
const operaId = ref();
const concatOperas = ref<Array<any>>([]);
const operaIds = ref<Array<any>>([]);
const title = ref<String>("");

const columns = reactive([
  { label: "Id", prop: "id", width: 80 },
  { label: "剧目", prop: "name", minWidth: 100 },
  { label: "标签", prop: "tags", slotName: "tags", minWidth: 200 },
  {
    label: "开投时间",
    prop: "promotionStartTime",
    slotName: "promotionStartTime",
    minWidth: 160,
  },
  {
    label: "已发布/总集数",
    prop: "updateEpisodeNo",
    slotName: "updateEpisodeNo",
    minWidth: 115,
  },
]);

// 提交拼剧
const emit = defineEmits(["success"]);
const confirmDialog = () => {
  let params = {
    operaId: operaId.value,
    subOperaId: selectionData.value.map((x: Record<string, any>) => {
      return x?.id;
    }),
  };
  if (params.subOperaId.length > 5)
    return ElMessage.error("最多选择五部剧拼接");
  setConcatOperas(params).then(() => {
    ElMessage.success(`剧目拼接成功`);
    closeDialog();
    emit("success");
  });
};

// 取消
const closeDialog = () => {
  selectionData.value = [];
  resetList();
};

// 重置
const resetList = () => {
  Object.assign(formData, form);
  dialogVisible.value = false;
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.pageNo = pageObj.pageNo;
  //   formData.pageSize = pageObj.pageSize;
  // } else {
  //   formData.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.pageSize = pageObj.pageSize = val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.pageNo = pageObj.pageNo;
  formData.pageSize = pageObj.pageSize;

  loading.value = true;
  operasSearch(formData)
    .then((res: Record<string, any>) => {
      tableData.value = res.data.map((item: Record<string, any>) => {
        item.premiereTime = moment(item.premiereTime + "Z").format(
          "YYYY-MM-DD HH:mm:ss"
        );
        item.promotionStartTime = moment(item.promotionStartTime + "Z").format(
          "YYYY-MM-DD HH:mm:ss"
        );
        /* 初始化的剧目id如果与当前页剧目id一致则选中，并且清除初始化剧目id中的这个id
         防止修改了选中状态后 切换分页后又重新选中
        */
        operaIds.value.map((m: number, i: number) => {
          if (m === item.id) {
            customTableRef.value.elTableRef.toggleRowSelection(item, true);
            delete operaIds.value[i];
          }
        });
        return item;
      });

      pageObj.total = Number(res?.total);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 清空选中
const clearBtn = () => {
  customTableRef.value.elTableRef.clearSelection();
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

const selectionChange = (val: Array<any>) => {
  selectionData.value = val;
};

const activeTime = (Time: string) => {
  let now = Date.now();
  let openTime = moment(Time).valueOf();
  return openTime > now ? true : false;
};

// 父级电子显示dialog
const showDialog = async (val: Record<string, any>, str = undefined) => {
  console.log("---显示分配分销商----**----", val);
  dialogVisible.value = true;
  title.value = val?.name;
  operaId.value = val?.id;
  await getconcatDetail(val?.id);
  getList();
};

//获取拼接的剧目
const getconcatDetail = (id: number) => {
  getConcatOperas(id)
    .then((res: any) => {
      concatOperas.value = cloneDeep(res);
      // 获取初始化第一次拼剧的剧目id
      operaIds.value = concatOperas.value.map((x) => x.id);
    })
    .finally(() => {
      loading.value = false;
    });
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.search_box {
  padding-left: 0;
  margin-top: -20px;

  :deep(.el-form-item) {
    margin-bottom: 10px;
  }
}

.table_box_wrapper {
  margin-top: -15px;

  :deep(.table_content) {
    padding: 10px 0;
  }

  .count_box {
    font-size: 16px;
  }

  .opera {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 6px;
    font-size: 14px;
  }
}
</style>
